package com.sgj.dao;

import com.sgj.pojo.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @author 沈国纪
 * @date 2021/3/31 14:11
 */
public interface BlogRepository extends JpaRepository<Blog, Long>, JpaSpecificationExecutor<Blog> {

	/**
	 * 根据分页条件查询博客
	 * @param pageable
	 * @return
	 */
	@Query("select b from Blog b where b.recommend = true")
	List<Blog> findTop(Pageable pageable);

	/**
	 * 根据查询条件查询对应博客
	 * @param query
	 * @param pageable
	 * @return
	 */
	@Query("select b from Blog b where b.title like ?1 or b.content like ?1")
	Page<Blog> findByQuery(String query, Pageable pageable);

	/**
	 * 浏览量+1
	 * @param id
	 * @return
	 */
	@Modifying
	@Query("update Blog b set b.views = b.views + 1 where b.id = ?1")
	int updateView(Long id);

	/**
	 * 按照年份分组
	 * @return
	 */
	@Query("select function('date_format', b.updateTime,'%Y') as year from Blog b group by function('date_format', b.updateTime,'%Y') order by year desc")
	List<String> findGroupYear();

	/**
	 * 根据年份查询对应博客
	 * @param year
	 * @return
	 */
	@Query("select b from Blog b where function('date_format', b.updateTime,'%Y') = ?1")
	List<Blog> findByYear(String year);
}
